package com.sgb.kjwl.view.ui.activity.house;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.tabs.TabLayout;
import com.sdk.mobile.manager.login.NoDoubleClickListener;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityLeaseHallMapBinding;
import com.sgb.kjwl.di.machine.DaggerMachineComponent;
import com.sgb.kjwl.di.machine.MachineModule;
import com.sgb.kjwl.model.entity.lease.DictEntity4;
import com.sgb.kjwl.model.entity.lease.LeaseMapEntity;
import com.sgb.kjwl.model.entity.request.LeaseHallMapFilterJson;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.utils.AbScreenUtils;
import com.sgb.kjwl.utils.KeyboardUtils;
import com.sgb.kjwl.view.ui.activity.lease.LeaseGaodeSearchView;
import com.sgb.kjwl.view.ui.activity.self.authentication.AuthActivity3;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.widget.DictWindow5;
import com.sgb.kjwl.view.widget.MapInfoDialog5;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.view.widget.lease.common.AskLeaseReleaseView;
import com.sgb.kjwl.viewmodel.house.LeaseHallMapModel;
import com.sgb.member.MemberConfig;
import com.sgb.member.entity.QualityMemberBean;
import com.sgb.member.ui.activity.ComApplyOrInvitePersonActivity;
import com.sgb.member.ui.activity.ComApplyOrInvitePersonShenPiActivity;
import com.sgb.member.ui.activity.MemberApplyJoinActivity;
import com.sgb.member.ui.activity.MemberInviteJoinActivity;
import com.sgb.member.ui.activity.PersonApplyJoinActivity;
import com.sgb.member.ui.activity.PersonInviteJoinActivity;
import com.sgb.member.weight.MemberCommonDialog;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.CommonDialog;
import com.swgk.core.mmkvutil.CacheMarker;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * 地图查找(出租)
 */
public class LeaseHallMapActivity extends AppActivity implements
        AMap.OnMarkerClickListener,
//        LocationSource,
//        AMapLocationListener,
        GeocodeSearch.OnGeocodeSearchListener,
        AMap.OnCameraChangeListener {

    @Inject
    LeaseHallMapModel viewModel;
    private ActivityLeaseHallMapBinding binding;
    //    private List<DictEntity4> data;
    private List<String> cityList = new ArrayList<>();
    private ThreeLevelAreaWindow mAddressPop;

    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;//省市区
    private List<DictEntity3> typeDictEntityList;//分类
    private DictWindow5 classifyWindow;//分类
    private DictWindow5 brandlWindow5;//类型
    private List<DictEntity3> brandDictEntityList;//类型
    private String categoryParentId = "";

    private String provinceName = "";
    private String cityName = "";
    private List<LeaseMapEntity> bundles = new ArrayList<>();
    private LeaseHallMapFilterJson filterJson = new LeaseHallMapFilterJson();
    private Bundle bundle = new Bundle();
    private AMap mAMap;//定位位置显示
    private AMapLocation location;
    private LocationSource.OnLocationChangedListener mListener;

    public AMapLocationClient mLocationClient = null;
    public AMapLocationClientOption mLocationOption = null;
    private GeocodeSearch geocoderSearch;//编码对象
    private MapInfoDialog5 mapInfoDialog5;
    private LatLng latLng;
    private String addressName;
    private String type = "";//租赁分类
    private String categoryFirst;//一级类型
    private String categorySecond;//二级类型
    private String categorySecondName;//二级类型名称

    private boolean isPublish = false;//是否为发布界面
    private boolean isRegeocodeQuery = true;//是否需要地理反编，用于解决移动地图时被动调用地理反编

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerMachineComponent.builder().appComponent(appComponent).machineModule(new MachineModule(this)).build().inject(this);
    }

    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, LeaseHallMapActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    public static void startForBundle(Context context, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(context, LeaseHallMapActivity.class);
        intent.putExtras(bundle);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    private void getArgument(Intent intent) {
        if (intent != null && intent.getExtras() != null) {
            bundle = intent.getExtras();
        }
        type = bundle.getString("type") == null ? "" : bundle.getString("type");
        categoryFirst = bundle.getString("categoryFirst", null);
        categorySecond = bundle.getString("categorySecond", null);
        categorySecondName = bundle.getString("categorySecondName");

        addressName = bundle.getString("text");
        latLng = new LatLng(bundle.getDouble("lat"), bundle.getDouble("lon"));
        if (TextUtils.isEmpty(addressName)) {//无具体地址返回时，通过经纬度反差详细地址
            isRegeocodeQuery = true;
            mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12));
        } else {
            isRegeocodeQuery = false;

            //当前界面不是发布界面时，移动到地图中心，并刷新数据
            if (!isPublish) {
                mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12));
                getAllList();
                //使用延迟方式赋值，解决自动触发etSearch change监听事件的问题
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        //解决短时间重复移动地图的重复跳转问题
                        binding.etSearch.setText(addressName);
                    }
                }, 2000);

            } else {
                binding.leaseLayout.setAddressText(addressName, String.valueOf(latLng.latitude), String.valueOf(latLng.longitude));
            }

            //第一次进入，并且工作地为空时，默认显示当前传递的地址
            if (TextUtils.isEmpty(binding.leaseLayout.getAddressText().trim())) {
                binding.leaseLayout.setAddressText(addressName, String.valueOf(latLng.latitude), String.valueOf(latLng.longitude));
            }

            new Handler().postDelayed(new Runnable() {
                public void run() {
                    //解决短时间重复移动地图的重复跳转问题
                    if (TextUtils.isEmpty(binding.etSearch.getText().toString().trim())) {
                        binding.etSearch.setText(addressName);
                    }
                }
            }, 2000);

        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        getArgument(intent);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_lease_hall_map);
        initMap(savedInstanceState);
        super.onCreate(savedInstanceState);
    }


    @Override
    protected void init() {
        getArgument(getIntent());
        viewModel.getAllSrarchType();
    }

    public void showTabList(List<DictEntity4> data) {
        if (data == null || data.size() == 0) return;
//        this.data = data;
        binding.tablayout.removeAllTabs();
        for (int i = 0; i < data.size(); i++) {
            String tabName = data.get(i).getValue();
            binding.tablayout.addTab(binding.tablayout.newTab().setText(tabName), false);
        }
        //设置默认筛选项
        if (!TextUtils.isEmpty(type)) {
            binding.tablayout.getTabAt(Integer.parseInt(type)).select();
        }
    }


    private void initTopLayout() {
//        binding.topLayout.titleView.setText("地图查找");
        binding.tablayout.addOnTabSelectedListener(new TabLayout.BaseOnTabSelectedListener() {
            /**
             * @param tab
             */
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                binding.selectLayout.setVisibility(View.VISIBLE);

                if (MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.LeaseMapGuide, true)) {
                    binding.rlUidingLayer.setVisibility(View.VISIBLE);
                    LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) binding.viewTop.getLayoutParams();
                    layoutParams.height = getResources().getDimensionPixelOffset(R.dimen.dp60) + binding.selectLayout.getLayoutParams().height;
                    binding.viewTop.setLayoutParams(layoutParams);
                }

                type = String.valueOf(tab.getPosition() + 1);//type 从1开始
                if ("3".equals(type)) {
                    binding.tvClassify.setText("车型");
                    binding.tvType.setText("品牌");
                    binding.typeLayout.setVisibility(View.VISIBLE);
                } else if ("6".equals(type)) {//工厂没有类型,需隐藏
                    binding.typeLayout.setVisibility(View.INVISIBLE);
                    binding.tvClassify.setText("分类");
                    binding.tvType.setText("类型");
                } else {
                    binding.typeLayout.setVisibility(View.VISIBLE);
                    binding.tvClassify.setText("分类");
                    binding.tvType.setText("类型");
                }
                updateChooseTextStatus(binding.classifyLayout, binding.tvClassify, 0, null);
                updateChooseTextStatus(binding.typeLayout, binding.tvType, 0, null);
                filterJson.setType(type);
                filterJson.setFirstCategory("");//重置分类
                filterJson.setSecondCategory("");
                if (!TextUtils.isEmpty(categoryFirst)) {//如果分类有值，代表是从外部传递的还未使用过，则第一次使用后立即清空，调用getFilterTypeModel会默认清空
                    filterJson.setFirstCategory(categoryFirst);
                }
                if (!TextUtils.isEmpty(categorySecond)) {
                    filterJson.setSecondCategory(categorySecond);
                }
                getAllList();
                viewModel.getFilterTypeModel(type);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }


    @Override
    protected void initView() {
        binding.classifyLayout.setOnClickListener(this);
        binding.typeLayout.setOnClickListener(this);
        binding.areaLayout.setOnClickListener(this);
        initTopLayout();
        initFilterView();
        initDrawerLayout();
        initUidingLayer();
        requestPermission();
    }

    private void initUidingLayer() {
        if (MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.LeaseMapGuide, true)) {
            binding.rlUidingLayer.setVisibility(View.VISIBLE);
        }
        binding.tvOk.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View view) {
                binding.rlUidingLayer.setVisibility(View.GONE);
                MkvUtils.get().putBoolean(MkvUtils.CommomData, CacheMarker.LeaseMapGuide, false);
            }
        });
    }

    private BottomSheetBehavior<RelativeLayout> bottomSheetBehavior;

    private void initDrawerLayout() {
        bottomSheetBehavior = BottomSheetBehavior.from(binding.contextLayout);
        bottomSheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                switch (newState) {
                    case BottomSheetBehavior.STATE_COLLAPSED://折叠状态
                        isPublish = false;
                        binding.titleView.setVisibility(View.GONE);
                        binding.titleView.setText("地图查找");
                        binding.ivBack.setTag("0");
                        binding.ivBack.setImageResource(R.mipmap.back);
                        binding.rlArrow.setVisibility(View.VISIBLE);
                        RelativeLayout.LayoutParams layoutParams2 = (RelativeLayout.LayoutParams) binding.leaseLayout.getLayoutParams();
                        layoutParams2.setMargins(0, AbScreenUtils.dp2px(LeaseHallMapActivity.this, 24), 0, 0);
                        binding.leaseLayout.setLayoutParams(layoutParams2);
                        break;
                    case BottomSheetBehavior.STATE_EXPANDED://完全展开
                        isPublish = true;
                        binding.titleView.setVisibility(View.VISIBLE);
                        binding.titleView.setText("发布需求");
                        binding.ivBack.setTag("1");
                        binding.ivBack.setImageResource(R.mipmap.ic_close_lease);
                        binding.ivBack.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                        binding.rlArrow.setVisibility(View.GONE);
                        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) binding.leaseLayout.getLayoutParams();
                        layoutParams.setMargins(0, 1, 0, 0);
                        binding.leaseLayout.setLayoutParams(layoutParams);
                        checkLoginAndAuth();
                        break;
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
            }
        });
        binding.leaseLayout.setOnCallBackListener(new AskLeaseReleaseView.OnCallBackListener() {
            @Override
            public void onCallClose(int type) {
                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                binding.tablayout.getTabAt(type).select();
            }

        });
        binding.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ("1".equals(view.getTag())) {
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                } else {
                    finish();
                }
            }
        });
        binding.tvPublish.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View view) {
                checkLoginAndAuth();
            }
        });
        binding.tvSearchDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.etSearch.setText("");
                binding.tvSearchDelete.setVisibility(View.GONE);
            }
        });
//        binding.etSearch.setOnClickListener(new NoDoubleClickListener() {
//            @Override
//            public void onNoDoubleClick(View view) {
////                isPublish = false;
////                isRegeocodeQuery = false;
////                ZulinGaodeSearchActivity.start(LeaseHallMapActivity.this, true, "");
//            }
//        });

        binding.leaseSearch.setSearchCity(viewModel.getAreaName());
        binding.leaseSearch.setEditText(binding.etSearch, binding.tvSearchDelete);
        binding.leaseSearch.setOnClallListener(new LeaseGaodeSearchView.CallListener() {
            @Override
            public void onCall(String address, double lat, double lon) {
                binding.etSearch.setText(address);
                latLng = new LatLng(lat, lon);
                isRegeocodeQuery = false;
                mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12));
                KeyboardUtils.hideSoftInput((Activity) LeaseHallMapActivity.this);
                binding.etSearch.clearFocus();
            }
        });

        binding.appBarLayout.post(this::setAppbarDragCallback);
    }

    private void setAppbarDragCallback() {
        CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) binding.appBarLayout.getLayoutParams();
        AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) params.getBehavior();
        if (behavior != null) {
            behavior.setDragCallback(new AppBarLayout.Behavior.DragCallback() {
                @Override
                public boolean canDrag(@NonNull AppBarLayout appBarLayout) {
                    return true;
                }
            });
        }
    }

    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //设置定位权限
            if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 100);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 100:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    if (isLocation) {
//                        mLocationClient.startLocation();//开启定位
//                    }
//                } else {//无定位权限，默认显示北京市东城区前门东大街11号 经纬度和地址
//                    if (isLocation) {
//                        LatLng lat = new LatLng(39.903114318847656, 116.39775848388672);
//                        mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(lat, 12));
//                        addMarker(latLng);
//                    }
                }
                return;
        }
    }


    private void initFilterView() {
        //分类选择
        classifyWindow = new DictWindow5(getActivity());
        classifyWindow.setFocusable(false);
        classifyWindow.setOutsideTouchable(false);
        classifyWindow.setOnCallBack(dictEntity -> {
            updateChooseTextStatus(binding.classifyLayout, binding.tvClassify, 2, dictEntity.getName());
            updateChooseTextStatus(binding.typeLayout, binding.tvType, 0, "不限");
            if (!"3".equals(type)) {
                //重置类型
                if (brandDictEntityList != null && brandDictEntityList.size() > 0) {
                    brandlWindow5.setCheckDefaultById(brandDictEntityList.get(0).getId());
                    filterJson.setSecondCategory(brandDictEntityList.get(0).getId());
                }
            }

            //设置筛选结果
            categoryParentId = dictEntity.getId();
            filterJson.setFirstCategory(dictEntity.getId());
            getAllList();
        });
        classifyWindow.setOnCloseBack(() -> {
            if ("分类".equals(binding.tvClassify.getText()) || "车型".equals(binding.tvClassify.getText())) {
                updateChooseTextStatus(binding.classifyLayout, binding.tvClassify, 0, null);
            } else {
                updateChooseTextStatus(binding.classifyLayout, binding.tvClassify, 2, null);
            }
        });

        //类型选择
        brandlWindow5 = new DictWindow5(getActivity());
        brandlWindow5.setFocusable(false);
        brandlWindow5.setOutsideTouchable(false);
        brandlWindow5.setOnCallBack(dictEntity -> {
            updateChooseTextStatus(binding.typeLayout, binding.tvType, 2, dictEntity.getName());
            filterJson.setSecondCategory(dictEntity.getId());
            getAllList();
        });
        brandlWindow5.setOnCloseBack(() -> {
            if ("类型".equals(binding.tvType.getText()) || "品牌".equals(binding.tvType.getText())) {
                updateChooseTextStatus(binding.typeLayout, binding.tvType, 0, null);
            } else {
                updateChooseTextStatus(binding.typeLayout, binding.tvType, 2, null);
            }
        });

        mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setBgView(binding.grayLayout);
        mAddressPop.setMemberHeight();
        mAddressPop.setProvinceSingle();
        mAddressPop.setCitySingle();
        mAddressPop.setAreaMore();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnResultClick((key1, key2, key3) -> {
            try {
                List<BaseAreaEntity> listKey1 = (List<BaseAreaEntity>) key1;
                List<BaseAreaEntity> listKey2 = (List<BaseAreaEntity>) key2;
                List<BaseAreaEntity> listKey3 = (List<BaseAreaEntity>) key3;
                filterJson.setAreaNos(getCityList(listKey3)); //获取区多选列表
                if (listKey2 != null && listKey2.size() > 0) {
                    cityName = listKey2.get(0).getName();
                    filterJson.setCityNo(listKey2.get(0).getNo());
                } else {
                    filterJson.setCityNo("");
                }
                filterJson.setProvinceNo(listKey1.get(0).getNo());
                provinceName = listKey1.get(0).getName();
            } catch (Exception exception) {
            }

            getAllList();
            if (!TextUtils.isEmpty(cityName) && "不限".equals(cityName)) {
                updateChooseTextStatus(binding.areaLayout, binding.tvArea, 2, cityName);
            } else {
                updateChooseTextStatus(binding.areaLayout, binding.tvArea, 2, provinceName);
            }

        });
        mAddressPop.setOnDismissListener(() -> {
            updateChooseTextStatus(binding.areaLayout, binding.tvArea, "地区".equals(binding.tvArea.getText()) ? 0 : 2, null);
        });

    }

    private List<String> getCityList(List<BaseAreaEntity> list) {
        cityList = new ArrayList<>();
        for (BaseAreaEntity entity : list) {
            if (!TextUtils.isEmpty(entity.getNo())) {
                cityList.add(entity.getNo());
            }
        }
        return cityList;
    }

    private void getAllList() {
        //        filterJson.setProvinceNo(viewModel.getAreaCodeModel());
        filterJson.setLatitude(latLng.latitude);
        filterJson.setLongitude(latLng.longitude);
        filterJson.setType(type);
        viewModel.getLeaseMapSearch(filterJson, false);
    }

    //初始化地图
    private void initMap(Bundle savedInstanceState) {
        binding.mapView.onCreate(savedInstanceState);
        geocoderSearch = new GeocodeSearch(getActivity());
        mAMap = binding.mapView.getMap();
        mAMap.setOnMarkerClickListener(this);
//        mAMap.setLocationSource(this);
        mAMap.setOnCameraChangeListener(this);//设置地图拖动监听
        geocoderSearch.setOnGeocodeSearchListener(this);

        //导航箭头定位的小图标，这里自定义一张图片
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.strokeWidth(0f);// 设置圆形的边框粗细
        myLocationStyle.anchor(0.5f, 0.7f);
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色  这样圆圈就没有了，看不到了
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
        mAMap.setMyLocationStyle(myLocationStyle);
//        mAMap.moveCamera(CameraUpdateFactory.zoomTo(16)); //缩放比例

        //设置amap的属性
        UiSettings settings = mAMap.getUiSettings();
        settings.setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        settings.setZoomControlsEnabled(false);//隐藏放大缩小

        //isHaveData 为true 说明有经纬度传过来，所以不需要在开启定位
//        if (isLocation) {
        mAMap.setMyLocationEnabled(false);//开启定位
//        } else {
//            mAMap.setMyLocationEnabled(false);//关闭定位
//        }
    }


    //设置一级分类数据
    public void showTypePopWindow(List<DictEntity3> data) {
        this.typeDictEntityList = data;
        if (data == null) {
            data = new ArrayList<>();
        }
        categoryParentId = filterJson.getFirstCategory();
        if (TextUtils.isEmpty(categoryParentId)) {
            categoryParentId = data.get(0).getId();
        }

        //设置 categoryFirst 的内容为已选项
        if (!TextUtils.isEmpty(categoryFirst)) {
            for (DictEntity3 entity : data) {
                if (entity.getId().equals(categoryFirst)) {
                    updateChooseTextStatus(binding.classifyLayout, binding.tvClassify, 2, entity.getPickerViewText());
                    updateChooseTextStatus(binding.typeLayout, binding.tvType, 2, categorySecondName);
                    categoryParentId = entity.getId();
                    categoryFirst = "";//使用一次后清空
                    categorySecond = "";//使用一次后清空
                    break;
                }
            }
        }

        classifyWindow.setData(data);
        classifyWindow.setCheckDefaultById(categoryParentId);
        filterJson.setFirstCategory(categoryParentId);

    }

    //设置二级分类数据
    public void showBrandPopWindow(List<DictEntity3> data) {
        this.brandDictEntityList = data;
        if (data == null) {
            data = new ArrayList<>();
        }
        String defaultId = filterJson.getSecondCategory();
        if (TextUtils.isEmpty(defaultId)) {
            defaultId = "";
        }

        //设置 categorySecond 的内容为已选项
        if (!TextUtils.isEmpty(categorySecondName)) {
            for (DictEntity3 entity : data) {
                if (entity.getPickerViewText().equals(categorySecondName)) {
                    updateChooseTextStatus(binding.typeLayout, binding.tvType, 2, entity.getPickerViewText());
                    defaultId = entity.getId();
                    break;
                }
            }
        }

        brandlWindow5.setData(data);
        brandlWindow5.setCheckDefaultById(defaultId);
        filterJson.setSecondCategory(defaultId);
    }

    private MarkerOptions markerOption1;

    public void showMapMark(List<LeaseMapEntity> datas) {
        try {
            bundles = datas;
            mAMap.clear();
            if (datas != null && datas.size() > 0) {
                for (int i = 0; i < datas.size(); i++) {
                    LeaseMapEntity entity = datas.get(i);
                    LatLng latLng = new LatLng(Double.parseDouble(entity.getLatitude()), Double.parseDouble(entity.getLongitude()));
//                        int icon = getIcon(entity.getType());
                    markerOption1 = new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_map_overlay_lease))
                            .position(latLng)
                            .period(1000)
                            .title(String.valueOf(i))
                            .infoWindowEnable(false)
                            .draggable(true);
                    mAMap.addMarker(markerOption1);
                }
//                addMarker(latLng);
                setMarket(latLng);
            } else {
//                Toast.makeText(getActivity(), "暂无数据", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    private int getIcon(String type) {
//        int icon = R.mipmap.ic_map_overlay_machine;
//        if ("1".equals(type)) {
//            icon = R.mipmap.ic_map_overlay_machine;
//        } else if ("2".equals(type)) {
//            icon = R.mipmap.ic_map_overlay_device;
//        } else if ("3".equals(type)) {
//            icon = R.mipmap.ic_map_overlay_car;
//        } else if ("4".equals(type)) {
//            icon = R.mipmap.ic_map_overlay_house;
//        } else if ("5".equals(type)) {
//            icon = R.mipmap.ic_map_overlay_land;
//        } else if ("6".equals(type)) {
//            icon = R.mipmap.ic_map_overlay_factory;
//        } else if ("7".equals(type)) {
//            icon = R.mipmap.ic_map_overlay_farm;
//        }
//        return icon;
//    }

    public void showAddressDatas(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data, String provinceNo) {
        if (data != null && data.size() > 0) {
            addressEntityList = data;
            filterJson.setProvinceNo(provinceNo);
            mAddressPop.setData(data, true, provinceNo);
        }
    }

    @Override
    public void onClick(View v) {
        checkDismiss(v.getId());
        switch (v.getId()) {
            case R.id.classify_layout://分类
                if ("分类".equals(binding.tvClassify.getText()) || "车型".equals(binding.tvClassify.getText())) {
                    updateChooseTextStatus(binding.classifyLayout, binding.tvClassify, -1, null);
                } else {
                    updateChooseTextStatus(binding.classifyLayout, binding.tvClassify, 1, null);
                }
                classifyWindow.setCheckDefaultById(filterJson.getFirstCategory());
                classifyWindow.showPopwindow(binding.classifyLayout);
                if (typeDictEntityList == null) {
                    viewModel.getFilterTypeModel(type);
                }
                break;
            case R.id.type_layout://类型
                if ("类型".equals(binding.tvType.getText()) || "品牌".equals(binding.tvType.getText())) {
                    updateChooseTextStatus(binding.typeLayout, binding.tvType, -1, null);
                } else {
                    updateChooseTextStatus(binding.typeLayout, binding.tvType, 1, null);
                }
                brandlWindow5.setCheckDefaultById(filterJson.getSecondCategory());
                brandlWindow5.showPopwindow(binding.typeLayout);
                viewModel.getFilterModelModel(type, categoryParentId);
                break;
            case R.id.area_layout://地区
                updateChooseTextStatus(binding.areaLayout, binding.tvArea, "地区".equals(binding.tvArea.getText()) ? -1 : 1, null);
                mAddressPop.showPopwindow(binding.areaLayout);
                if (addressEntityList == null) {
                    viewModel.getCityData();
                }
                break;
        }
    }

    private void checkDismiss(int rid) {
        if (rid != R.id.classify_layout && classifyWindow != null && classifyWindow.isShowing()) {
            classifyWindow.dismiss();
        }
        if (rid != R.id.type_layout && classifyWindow != null && brandlWindow5.isShowing()) {
            brandlWindow5.dismiss();
        }
        if (rid != R.id.area_layout && classifyWindow != null && mAddressPop.isShowing()) {
            mAddressPop.dismiss();
        }
    }

    //更新选项颜色
    private void updateChooseTextStatus(View view, TextView textView, int value, String name) {
        if (!TextUtils.isEmpty(name)) {
            textView.setText(name);
        }
        if (value == 0) {
            setTextViewBg(view, textView, R.drawable.search_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333);
        } else if (value == -1) {
            setTextViewBg(view, textView, R.drawable.search_bg, R.mipmap.ic_up_arrow_n, R.color.color_333333);
        } else if (value == 1) {
            setTextViewBg(view, textView, R.drawable.search_new_blue_bg, R.mipmap.icon_up_red, R.color.color_main);
        } else if (value == 2) {
            setTextViewBg(view, textView, R.drawable.search_new_blue_bg, R.mipmap.icon_down_red, R.color.color_main);
        }
    }

    //设置背景色和图标
    private void setTextViewBg(View view, TextView textView, int bg, int img, int textColor) {
        view.setBackgroundResource(bg);
        Drawable drawable_n = getResources().getDrawable(img);
        drawable_n.setBounds(0, 0, drawable_n.getMinimumWidth(), drawable_n.getMinimumHeight());
        textView.setCompoundDrawables(null, null, drawable_n, null);
        textView.setTextColor(getResources().getColor(textColor));
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
        binding.appBarLayout.setExpanded(false);
    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
//        if (isLocation) {
//            latLng = cameraPosition.target;
//            getAddress(latLng);
//        }
        if (isRegeocodeQuery) {
            latLng = cameraPosition.target;
            getAddress(latLng);
            getAllList();
        }
        isRegeocodeQuery = true;
    }

    /**
     * 根据经纬度得到地址
     */
    public void getAddress(final LatLng latLng) {
        LatLonPoint latLonPoint = new LatLonPoint(latLng.latitude, latLng.longitude);
        // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 500, GeocodeSearch.AMAP);
        geocoderSearch.getFromLocationAsyn(query);// 设置同步逆地理编码请求
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
        if (rCode == 1000) {
            if (result != null && result.getRegeocodeAddress() != null
                    && result.getRegeocodeAddress().getFormatAddress() != null) {
                addressName = result.getRegeocodeAddress().getFormatAddress();// 逆转地里编码不是每次都可以得到对应地图上的opi

                //当前界面不是发布界面时，移动到地图中心，并刷新数据
                if (isPublish) {
                    binding.leaseLayout.setAddressText(addressName, String.valueOf(latLng.latitude), String.valueOf(latLng.longitude));
                } else {
                    if (!TextUtils.isEmpty(binding.etSearch.getText())) {//如果搜索地址不为空，则代表非第一次进入该界面
                        binding.llAddIcon.setVisibility(View.GONE);
                    }
                    binding.etSearch.setText(addressName);
                    binding.etSearch.clearFocus();
                }

                //第一次进入，并且工作地为空时，默认显示当前传递的地址
                if (TextUtils.isEmpty(binding.leaseLayout.getAddressText().trim())) {
                    binding.leaseLayout.setAddressText(addressName, String.valueOf(latLng.latitude), String.valueOf(latLng.longitude));
                }
                if (TextUtils.isEmpty(binding.etSearch.getText().toString().trim())) {
                    binding.etSearch.setText(addressName);
                    binding.etSearch.clearFocus();
                }
            }
        }
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        showMarkerView(marker);
        return true;
    }

//    @Override
//    public void activate(LocationSource.OnLocationChangedListener onLocationChangedListener) {
//        mListener = onLocationChangedListener;
//        //初始化定位
//        mLocationClient = new AMapLocationClient(getActivity());
//        //设置定位回调监听
//        mLocationClient.setLocationListener(this);
//
//        //初始化定位参数
//        mLocationOption = new AMapLocationClientOption();
//        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
//        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//        //设置是否返回地址信息（默认返回地址信息）
//        mLocationOption.setNeedAddress(true);
//        //设置是否只定位一次,默认为false
//        mLocationOption.setOnceLocation(false);
//        //设置是否强制刷新WIFI，默认为强制刷新
//        mLocationOption.setWifiActiveScan(true);
//        //设置是否允许模拟位置,默认为false，不允许模拟位置
//        mLocationOption.setMockEnable(false);
//        //设置定位间隔,单位毫秒,默认为2000ms
//        mLocationOption.setInterval(2000 * 10);
//        //给定位客户端对象设置定位参数
//        mLocationClient.setLocationOption(mLocationOption);
//        //启动定位
//        mLocationClient.startLocation();
//    }
//
//    @Override
//    public void deactivate() {
//        mListener = null;
//        if (mLocationClient != null) {
//            mLocationClient.stopLocation();
//            mLocationClient.onDestroy();
//        }
//    }
//
//    @Override
//    public void onLocationChanged(AMapLocation aMapLocation) {
//        location = aMapLocation;
//        if (mListener != null && location != null) {
//            if (location != null && location.getErrorCode() == 0) {
//                mListener.onLocationChanged(location);// 显示系统箭头
//                mLocationClient.stopLocation();
////                if (isLocation) {
////                    latLng = new LatLng(location.getLatitude(), location.getLongitude());
////                    getAllList();
////                }
//            }
//        } else {
////            Toast.makeText(getActivity(), "无法获取当前位置,请输入使用地点", Toast.LENGTH_SHORT).show();
//        }
//    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        binding.mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onResume() {
        super.onResume();
        binding.mapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        binding.mapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        binding.mapView.onDestroy();
    }

    private MarkerOptions markerOption;

//    private void addMarker(LatLng la) {
//        markerOption = new MarkerOptions()
//                .position(la)
//                .period(1000)
//                .icon(BitmapDescriptorFactory.fromResource(R.mipmap.map_location))
//                .draggable(true);
//        mAMap.addMarker(markerOption).hideInfoWindow();
//        binding.mapView.invalidate();
//        mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12));
//    }

    private Marker mGPSMarker;

    private void setMarket(LatLng latLng) {
        if (mGPSMarker != null) {
            mGPSMarker.remove();
        }
        //获取屏幕宽高
        WindowManager wm = getWindowManager();
        int width = (wm.getDefaultDisplay().getWidth()) / 2;
        int height = ((wm.getDefaultDisplay().getHeight()) / 2) - 200;
        markerOption = new MarkerOptions();
        markerOption.draggable(false);
        markerOption.icon(BitmapDescriptorFactory.fromResource(R.mipmap.map_location));
        //设置一个角标
        mGPSMarker = mAMap.addMarker(markerOption);
        //设置marker在屏幕的像素坐标
        mGPSMarker.setPosition(latLng);
        //设置像素坐标
        mGPSMarker.setPositionByPixels(width, height);
//        binding.mapView.invalidate();
//        isRegeocodeQuery = false;
    }

    //展示地图覆盖物
    private void showMarkerView(Marker marker) {
        LeaseMapEntity data = bundles.get(Integer.parseInt(marker.getTitle()));
        if (data != null) {
            if (mapInfoDialog5 == null) {
                mapInfoDialog5 = new MapInfoDialog5(getActivity());
                mapInfoDialog5.setFocusable(false);
                mapInfoDialog5.setOutsideTouchable(true);
                mapInfoDialog5.setCallBackListener(new MapInfoDialog5.CallBackListener() {
                    @Override
                    public void onClickItem(LeaseMapEntity entity) {
                        //详情
                        if (TextUtils.isEmpty(entity.getType())) return;
                        if ("7".equals(type)) {
                            viewModel.getH5Url(7, entity.getNo());
                        } else {
                            viewModel.getH5Url(Integer.parseInt(entity.getType()), entity.getDataId());
                        }
                    }

                    @Override
                    public void onCallExchange(LeaseMapEntity entity) {
                        //交流
                        if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                            VerificationCodeLoginActivity.start(getActivity());
                        } else {
                            if (!TextUtils.isEmpty(entity.getCustomerServiceId())) {
                                viewModel.findCustomerServiceImAccount(entity.getCustomerServiceId());
                            } else {
                                checkAllowDialog("对方未设置客服人员，不支持交流。");
                            }
                        }
                    }

                    @Override
                    public void onCallInvite(final LeaseMapEntity entity) {
                        if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                            VerificationCodeLoginActivity.start(LeaseHallMapActivity.this);
                        } else {
                            //当前用户为个人时
                            if (SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0) == 0) {
                                if ("1".equals(entity.getBusiness_type())) {//判断发布者为企业时，无需权限判断，直接进入邀请页面
                                    toMemberInvite(entity);
                                } else {
                                    MToast.showToast(LeaseHallMapActivity.this, "功能开发中");
                                }
                            } else {//当前用户为企业时,判断权限
                                if (!MemberConfig.getInstance().isHavePermission("14_yaoqinghuiyuan1")) {//邀请加盟权限
                                    MToast.showToast(getActivity(), "没有权限操作，请找企业管理员分配权限");
                                    return;
                                }else{
                                    toMemberInvite(entity);
                                }
                            }
                        }
                    }

                });
            }
            if (!mapInfoDialog5.isShowing()) {
                mapInfoDialog5.showAtLocation(binding.coordinatorLayout, Gravity.BOTTOM, 0, 0);
            }
            mapInfoDialog5.setData(data);
        }
    }

    //检测收费登录和认证
    public void checkLoginAndAuth() {
        if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            showDialogLogin("请先完成登录，并实名认证成功后可进行需求发布操作");
        } else {
            boolean manager = SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false);
            if (manager) {
                binding.leaseLayout.setDefaultData();
                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
            } else {
                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                showDialogAuth();
            }
        }
    }

    //邀请功能
    public void toMemberInvite(LeaseMapEntity entity) {
        try {
            QualityMemberBean bean = new QualityMemberBean();
            bean.setNo(entity.getCreateCompanyNo());
            bean.setCompanyNo(entity.getCreateCompanyNo());
            bean.setCompanyName(entity.getBusiness_name());
            bean.setUserType(entity.getBusiness_type());//1:企业，2个人
            bean.setUserTypeName(entity.getBusiness_name());
            bean.setApproveType("2");
            //邀请
            if("2".equals(entity.getBusiness_type())){//个人
                bean.setNo(entity.getPublisherUserNo());
                bean.setCompanyNo(entity.getPublisherUserNo());
                bean.setCompanyName(entity.getPublisherName());
            }

            String mApproveType = "";
            if ("2".equals(bean.getApproveType())) {//邀请
                mApproveType = "inviteJoinCompany";
            } else {
                mApproveType = "applyJoinCompany";
            }

            String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
            if(companyNo.equals(entity.getCreateCompanyNo())){//判断是否为同企业
                MToast.showToast(getActivity(), "此信息为同企业发布，不能进行邀请操作");
                return;
            }
            viewModel.getProcessStatus(companyNo, mApproveType, bean);
        } catch (Exception e) {
        }
    }

    public void updateProcessStatus(String status, QualityMemberBean memberBean) {
        // 有审批时：弹出审批确认弹窗，具体如原型所示，点击去填写跳转到邀请审批信息填写页
        // 无审批时：点击去填写跳转到邀请信息填写页
        if (status.equals("1")) {
            MemberCommonDialog dialog = new MemberCommonDialog(new MemberCommonDialog.SimpleListener() {
                @Override
                public void onPositive(Object... objects) {
                    // 跳转填写审批信息// 审批类型 1 申请加盟(固定传1就行) 2邀请加盟
                    jumpJoinPage(status, memberBean);
                }
            }, MemberCommonDialog.STYLE_INVITE_JOIN);
            dialog.show(LeaseHallMapActivity.this, "MemberCommonDialog");
        } else {
            jumpJoinPage(status, memberBean);
        }
    }

    private void jumpJoinPage(String status, QualityMemberBean memberBean) {
        // 跳转邀请加盟申请页
        switch (memberBean.getApproveType()) {
            case "2": // 邀请加盟
                if (MemberConfig.getInstance().getComType() == MemberConfig.WEBSITE_FOR_PERSONAL) {
                    PersonInviteJoinActivity.start(LeaseHallMapActivity.this, memberBean, false);//个人 邀请 企业
                } else {
                    if (memberBean.getUserType().equals("1")) {
                        MemberInviteJoinActivity.start(LeaseHallMapActivity.this, memberBean);//企业 邀请 企业
                    } else {
                        if (status.equals("1")) {//有审批
                            ComApplyOrInvitePersonShenPiActivity.start(LeaseHallMapActivity.this, memberBean, false, 0);
                        } else {
                            ComApplyOrInvitePersonActivity.start(LeaseHallMapActivity.this, memberBean, false, 0); //    企业  邀请  个人
                        }
                    }
                }
                break;
            case "1": // 申请加盟
                if (MemberConfig.getInstance().getComType() == MemberConfig.WEBSITE_FOR_PERSONAL) {
                    PersonApplyJoinActivity.start(LeaseHallMapActivity.this, memberBean, false);//个人 申请 企业
                } else {
                    if (memberBean.getUserType().equals("1")) {
                        MemberApplyJoinActivity.start(LeaseHallMapActivity.this, memberBean);//企业 申请 企业
                    } else {
                        if (status.equals("1")) {//有审批
                            ComApplyOrInvitePersonShenPiActivity.start(LeaseHallMapActivity.this, memberBean, false, 1);
                        } else {
                            ComApplyOrInvitePersonActivity.start(LeaseHallMapActivity.this, memberBean, false, 1);  //    企业  申请  个人
                        }
                    }
                }
                break;
        }
    }

    /**
     * 登录提示
     */
    private void showDialogLogin(String text) {
        new CommonDialog(this).builder().setPositiveButton("去登录").setNegativeButton("取消")
                .setTitle("温馨提示")
                .setMsg(text)
                .setCancelable(false)
                .setDialogCallBack(new CommonDialog.DialogCallBack() {
                    @Override
                    public void onRightClick() {
                        VerificationCodeLoginActivity.start(getActivity());
                    }

                    @Override
                    public void onLeftClick() {

                    }
                }).show();
    }

    /**
     * 认证提示
     */
    private void showDialogAuth() {
        new CommonDialog(this).builder().setPositiveButton("立即认证").setNegativeButton("取消")
                .setTitle("温馨提示")
                .setMsg("请认证为实名用户/企业用户才可发布需求信息")
                .setCancelable(false)
                .setDialogCallBack(new CommonDialog.DialogCallBack() {
                    @Override
                    public void onRightClick() {
                        AuthActivity3.start(LeaseHallMapActivity.this);
                    }

                    @Override
                    public void onLeftClick() {

                    }
                }).show();
    }

    public void checkAllowDialog(String msg) {
        if (TextUtils.isEmpty(msg)) {
            msg = "对方未设置客服人员，不支持交流。";
        }
        new CommonDialog(this).builder().setPositiveButton("我知道了")
                .setTitle("温馨提示")
                .setMsg(msg)
                .setCancelable(false)
                .setDialogCallBack(new CommonDialog.DialogCallBack() {
                    @Override
                    public void onRightClick() {

                    }

                    @Override
                    public void onLeftClick() {

                    }
                }).show();
    }
}
